package com.qfedu.fmmall.controller;

import com.github.wxpay.sdk.WXPay;
import com.qfedu.fmmall.config.ExceptionR;
import com.qfedu.fmmall.config.MyPayConfig;
import com.qfedu.fmmall.entity.Orders;
import com.qfedu.fmmall.service.OrdersService;
import com.qfedu.fmmall.vo.ResultVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/order")
@Api(value = "提供订单相关的操作接口",tags = "订单管理")
public class OrderController {

     @Autowired
    private OrdersService orderService;

    @ApiOperation("用户提交订单接口")
    @PostMapping("/add")
    @ApiImplicitParam(name = "cids",value = "商品id",required = true,dataType = "String")
    public ResultVO add( String cids, @RequestBody Orders orders){
        ResultVO resultVO = new ResultVO();
        try {
//            保存订单
             resultVO= orderService.add(cids,orders);
              Orders order=(Orders)resultVO.getData();
              if (order!=null&&order.getOrderId()!=null){
                  //             微信支付请求链接
                  WXPay wxPay=new WXPay(new MyPayConfig());
                  HashMap<String, String> map = new HashMap<>();
                  HashMap<String, String> orderInfo = new HashMap<>();
                  orderInfo.put("orderId", order.getOrderId());
                  orderInfo.put("productNames",order.getUntitled());
                  map.put("body",order.getUntitled());
                  map.put("out_trade_no",order.getOrderId());
                  map.put("fee_type","CNY");
                  map.put("total_fee","1");
                  map.put("trade_type","NATIVE");
                  map.put("notify_url","http://ali.free.idcfengye.com/pay/callback");
                  Map<String, String> resp = wxPay.unifiedOrder(map);
                  orderInfo.put("payUrl",resp.get("code_url"));
//                  orderInfo.put("totalPrice","");
                  System.out.println(resp);
                  resultVO=ResultVO.success(orderInfo,"提交订单成功！");
              }else {
                  resultVO= ResultVO.error("提交订单失败，没有订单号");
              }
        }catch (ExceptionR e){
            resultVO= ResultVO.error(e.getMessage());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return resultVO;
    }

    /**
     * 查询订单状态
     * @param orderId
     * @return
     */
    @ApiOperation(value = "查询订单状态",tags = {"查询订单状态"})
    @GetMapping("/status/{orderId}")
    @ApiImplicitParams({@ApiImplicitParam(name = "orderId",value = "订单id",dataType = "String")})
    public ResultVO getById(@PathVariable("orderId") String orderId){
        return orderService.getOrdersStatus(orderId);
    }

}
